package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {

        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 登录用户效验
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 2-1 获取用户id
        Integer userId = user.getId();

        // 3. 获取文章id
        Long entryId = dto.getEntryId();
        // 3-1 获取用户操作类型
        Short operation = dto.getOperation();

        // 4. 判断用户操作类型
        if (0 == operation) {

            // 去重
            Object o = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
            if (o != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不可重复点击");
            }

            // 保存数据(收藏)
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString(), JSON.toJSONString(dto));

        } else {

            // 删除收藏
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
        }

        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}

